package training.exception;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ExceptionDemo {

	public int divide(int a, int b) throws InvalidArgumentException {
		if (a > 1000 || b <= 0) {

			// both the lines below are valid. commented first one just to
			// support throw exception line next.
			// throw new
			// InvalidArgumentException("either a or b has invalid value");

			InvalidArgumentException exception = new InvalidArgumentException(
					"either a or b has invalid value");
			throw exception;
			// System.out.println("this line will never be executed");

		}
		return a / b;

	}

	public static void main(String[] args) throws FileNotFoundException {
		/* 
		//try catch syntax
		try{
			
		}catch(Exception e){
			
		}
		finally{
			
		}
		
		*/
		
		
		ExceptionDemo demo = new ExceptionDemo();
		demo.anotherExceptionDemo();
		
	}
	
	public void exceptionDemo(){
		ExceptionDemo demo = new ExceptionDemo();
		try {
			
			System.out.println(demo.divide(4, 2));
			
			System.out.println(demo.divide(4, 0));
			System.out.println("This will not be exedcuted");
			
		}
		
		/** typical catching of multiple exceptions 
		 * 
		 */
		/*
		catch(InvalidArgumentException e){
			
		}
		catch(ArithmeticException e1){
			
		}
		*/
		/**
		 * Java 7 way of catching multiple exceptions.
		 */
		catch (InvalidArgumentException | ArithmeticException e) {
			
			e.printStackTrace();
		}
		finally{
			System.out.println("This will be exedcuted always");
		}
		
		//System.out.println(100/0); //this throws ArithmaticException / by zero

		/**
		FileInputStream fis1 = new FileInputStream("input.txt");

		try {
			FileInputStream fis = new FileInputStream("input.txt");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		**/
		// ArithmeticException exception;
	}
	
	public void anotherExceptionDemo(){
		
		
		String[] names = new String[]{"Nisha","Ambika","Prathima"};
		try{
		System.out.println(names[5]);
		}catch(ArrayIndexOutOfBoundsException e){
			System.err.println("ArrayIndexOUtOfBoundsException occurred : "  + e.getMessage());
			//you can write regular java code, including throwing new exception or having try catch block also within a catch block.
			//but remember this is only for handling exception scenarios, so your attention is required.
		}
		
	}

}
